<template>
  <div class="result-entry-container">
    <!-- 左侧：原始记录表 -->
    <div class="left-form">
      <div style="display: flex;flex-direction: row-reverse; gap: 10px;">
        <el-button
          size="mini"
          type="primary"
          @click="openSpectrumUpload"
          icon="el-icon-upload2"
        >
          上传实验室原始记录表
        </el-button>
        <el-button
          size="mini"
          type="primary"
          @click="openFileUploadDialog"
          icon="el-icon-upload2"
        >
          导入仪器结果
        </el-button>
        <el-dropdown
          size="mini"
          split-button
          type="success"
          icon="el-icon-download"
          @click="downloadEditedTableAs('word')"
          @command="downloadEditedTableAs"
          :disabled="!parsedTables || parsedTables.length === 0"
        >
          下载表格
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item command="html">HTML格式</el-dropdown-item> -->
            <el-dropdown-item command="word">导出Word(.docx)</el-dropdown-item>
            <el-dropdown-item command="xlsx">导出Excel(.xlsx)</el-dropdown-item>
            <el-dropdown-item command="pdf">导出PDF(.pdf)</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-edit"
          @click="toggleEditMode"
          :disabled="!parsedTables || parsedTables.length === 0"
        >
          {{ isEditMode ? "退出编辑" : "编辑表格" }}
        </el-button>
      </div>
      <!-- 修改为遍历展示多个表格 -->
      <div v-for="(table, index) in parsedTables" :key="index">
        <div
          v-html="table"
          class="dynamic-table"
          :class="{ 'edit-mode': isEditMode }"
          @click="handleTableCellClick"
        ></div>
        <!-- 在表格之间添加分隔线 -->
        <div v-if="index < parsedTables.length - 1" class="table-divider"></div>
      </div>
    </div>

    <!-- 右侧：检测结果录入 -->
    <div class="right-form">
      <div style="display: flex;justify-content: space-between;height: 55px;">
        <h2>检测结果录入</h2>
        <!-- 按钮组 -->
        <div class="button-group">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="success" @click="submit">提交复核</el-button>
        </div>
      </div>
      <!-- 检测仪器选择 -->
      <el-form
        :model="formData"
        label-width="100px"
        size="small"
        style="margin-bottom: 20px;"
        :rules="equipmentRules"
        ref="equipmentForm"
      >
        <el-form-item
          label="项目名称："
          style="background: #fff;border-radius: 15px;margin-top: 10px;height: 50px;padding-top: 10px;"
        >
          {{ this.batchData[0].projectName }}
        </el-form-item>
        <el-form-item
          label="受检单位："
          style="background: #fff;border-radius: 15px;margin-top: 10px;height: 50px;padding-top: 10px;"
        >
          {{ this.batchData[0].inspectionName }}
        </el-form-item>
        <el-form-item
          label="检测仪器："
          prop="equipmentType"
          style="background: #fff;border-radius: 15px;margin-top: 10px;height: 70px;padding-top: 20px;"
        >
          <el-row>
            <el-col :span="7">
              <el-select
                v-model="equipmentType"
                placeholder="仪器分类"
                style="width: 100%;"
                @change="handleChangeEqu"
              >
                <el-option
                  v-for="(item, index) in level"
                  :key="index"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-select
                v-model="equipmentClass"
                clearable
                placeholder="仪器型号"
                style="width: 100%;"
                @change="handleChangeEquType"
              >
                <el-option
                  v-for="(item, index) in levelTwo"
                  :key="index"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-select
                v-model="checkEquipment"
                clearable
                placeholder="仪器编号"
                style="width: 100%;"
                value-key="equipmentNumber"
              >
                <el-option
                  v-for="item in levelThree"
                  :key="item.equipmentNumber"
                  :label="item.equipmentNumber"
                  :value="item"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <!-- 样品1 -->
      <div class="sample-group">
        <el-form label-width="100px" label-position="left">
          <div
            v-for="(item, index) in batchData"
            :key="index"
            class="factor-section factor-package"
          >
            <div v-if="item.isFactor == 0" class="factor-package-item">
              <el-form-item label="样品编号:">{{ item.sampleNo }}</el-form-item>
              <el-form-item label="检测因子:">{{
                item.factorName
              }}</el-form-item>
              <el-form-item label="检测结果:">
                <el-row>
                  <!-- <el-col
                    :span="4"
                    style="text-align: right;padding-bottom: 5px;"
                  >
                    <span class="text-ellipsis" :title="item.checkRes.name">
                      {{ item.checkRes.name }}:
                    </span>
                  </el-col> -->
                  <el-col
                    :span="9"
                    style="margin-left:10px;padding-bottom: 5px;"
                  >
                    <el-input
                      v-model="item.checkRes.v1"
                      type="Number"
                      controls-position="right"
                      :min="0"
                      placeholder="结果值"
                      style="width: 100%;"
                    >
                      <template slot="append"
                        >E</template>
                    </el-input>
                  </el-col>
                  <el-col
                    :span="9"
                    style="margin-left:10px;padding-bottom: 5px;"
                  >
                    <el-input
                      v-model="item.checkRes.v2"
                      type="Number"
                      controls-position="right"
                      :min="0"
                      placeholder="幂数"
                      style="width: 100%;"
                    >
                      <template v-if="item.unitName" slot="append">{{
                        item.unitName
                      }}</template>
                    </el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </div>

            <!-- 因子套餐 -->
            <div
              v-else-if="item.isFactor == 1"
              class="factor-section factor-package"
            >
              <div
                v-for="(items, indexs) in Array.isArray(item.factorSubsetVos)
                  ? item.factorSubsetVos
                  : [item.factorSubsetVos]"
                :key="indexs"
                class="factor-package-item"
              >
                <el-form-item label="样品编号:">{{
                  items.sampleNo || item.sampleNo
                }}</el-form-item>
                <el-form-item label="检测因子:">{{
                  items.factorName
                }}</el-form-item>
                <el-form-item label="检测结果:">
                  <el-row>
                    <!-- <el-col
                      :span="4"
                      style="text-align: right;padding-bottom: 5px;"
                    >
                      <span
                        class="text-ellipsis"
                        :title="items.checkSubRes.name"
                      >
                        {{ items.checkSubRes.name }}:
                      </span>
                    </el-col> -->
                    <el-col :span="10">
                      <el-input
                        v-model="items.checkSubRes.v1"
                        type="Number"
                        controls-position="right"
                        :min="0"
                        placeholder="结果值"
                        style="width: 100%;"
                      >
                        <template slot="append"
                          >E</template>
                      </el-input>
                    </el-col>
                    <el-col :span="10">
                      <el-input
                        v-model="items.checkSubRes.v2"
                        type="Number"
                        controls-position="right"
                        :min="0"
                        placeholder="幂数"
                        style="width: 100%;"
                      >
                        <template v-if="items.unitName" slot="append">{{
                          items.unitName
                        }}</template>
                      </el-input>
                    </el-col>
                  </el-row>
                </el-form-item>
              </div>
            </div>
          </div>
          <div class="result-tips">
            <div class="tip-item">
              例:3.45E2=3.45×10² ; 234E0=234 ; 1.62E-3=1.62×10⁻³
            </div>
            <div class="tip-item tip-warning">
              无子因子的：输入0代表未检出
            </div>
            <div class="tip-item tip-warning">
              有子因子的：输入0代表未检出，不填代表未检查此项
            </div>
          </div>
        </el-form>
      </div>
    </div>

    <el-dialog title="提交复核" :visible.sync="reviewDialogVisible" width="400px">
      <div style="margin-bottom: 20px;">
        <el-form label-width="100px">
          <el-form-item
            prop="reviewer"
            label="选择复核人:"
            label-width="100px"
            clearable
          >
            <el-select
              v-model="reviewer"
              placeholder="请选择复核人"
              filterable
              value-key="userId"
              style="width:100%"
            >
              <el-option
                v-for="item in usernameOptions"
                :key="item.userId"
                :label="item.empName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </span>
    </el-dialog>

    <!-- 文件上传弹框 (添加到模板末尾) -->
    <el-dialog
      title="导入仪器结果文件"
      :visible.sync="fileUploadVisible"
      width="400px"
    >
      <el-upload
        ref="upload"
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :before-upload="beforeOriginalRecordUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>

      <div v-if="selectedFile" style="margin-top: 10px;">
        已选择文件: {{ selectedFile.name }}
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="fileUploadVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmFileUpload"
          :disabled="!selectedFile"
        >
          确 定上传
        </el-button>
      </span>
    </el-dialog>

    <!-- 样品号选择弹框 (如果需要) -->
    <el-dialog title="选择样品号" :visible.sync="sampleSelectDialogVisible" width="20%">
      <el-form>
        <el-form-item label="样品号">
          <el-select
            v-model="selectedSampleNo"
            placeholder="请选择样品号"
            style="width: 100%"
          >
            <el-option
              v-for="item in sampleOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sampleSelectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSampleSelection"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 上传原始记录表弹框 -->
    <el-dialog
      title="上传实验室原始记录表"
      :visible.sync="spectrumDialogVisible"
      width="400px"
      @close="handleSpectrumDialogClose"
    >
      <el-upload
        ref="spectrumUpload"
        class="upload-demo"
        drag
        action="/api/checkTaskGroup/pcFileUpload"
        :on-preview="handleSpectrumPreview"
        :on-remove="handleSpectrumRemove"
        :before-remove="beforeSpectrumRemove"
        :on-change="handleSpectrumChange"
        :before-upload="beforeSpectrumUpload"
        :on-success="handleSpectrumSuccess"
        name="files"
        multiple
        :file-list="spectrumFileList"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>

      <div v-if="selectedSpectrumFile" style="margin-top: 10px;">
        已选择文件: {{ selectedSpectrumFile.name }}
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="spectrumDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitSpectrumFiles"
        >
          确 定上传
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as List from "@/api/List";
import * as batchesServer from "@/api/batches";
export default {
  name: "ResultEntry",
  data() {
    return {
      formData: {},
      batchData: {},
      tableHtml: "",
      tableStyle: "",
      parsedTable: "",
            reviewDialogVisible: false,
      
      // 选择样品号对话框可见性控制
      sampleSelectDialogVisible: false,
      usernameOptions: [],
      reviewer: "",
      level: [],
      levelTwo: [],
      levelThree: [],
      equipmentType: "",
      equipmentClass: "",
      checkEquipment: "",
      checkFactorIds: "",
      batchNumber: "",
      checkFactorId: "",
      checkTaskId: "",
      jobId: "",
      flatDataList: [],
      mockData: [],
      parsedTables: [],
      checkEquipmentname: "",
      equipmentRules: {
        equipmentType: [
          { required: true, message: "请选择仪器分类", trigger: "blur" }
        ]
      },
      isEditMode: false, // 编辑模式开关
      editedTables: [], // 存储编辑后的表格内容
      // 文件上传相关数据
      fileUploadVisible: false,
      selectedFile: null,
      currentRow: null,
      // 样品号选择相关
      dialogVisible: false,
      sampleOptions: [],
      selectedSampleNo: "",
      // 上传原始记录表相关数据
      spectrumDialogVisible: false,
      spectrumFileList: [], // 用于回显已上传的文件
      uploadSuccessCount: 0,
      uploadTotalCount: 0,
      uploadFailedCount: 0
    };
  },
  activated() {
    // 获取路由查询参数
    this.checkFactorIds = this.$route.params.checkFactorIds || "";
    this.checkFactorId = this.$route.params.checkFactorId || "";
    this.batchNumber = this.$route.params.batchNumber || "";
    this.checkTaskId = this.$route.params.checkTaskId || "";
    this.jobId = this.$route.params.jobId || "";
    this.batcData = this.$route.params.batcData || "";
    this.updateStyle();
    this.handleSearch();
    this.getEquipment();
    this.handleCreate();
  },
  methods: {
    handleSearch() {
      batchesServer
        .getTemplates({
          checkFactorId: this.checkFactorId
        })
        .then(res => {
          console.log("获取到的模板文件", res);

          // 清空之前的数据
          this.mockData = [];
          this.tableHtml = "";
          this.tableStyle = "";

          if (Array.isArray(res.result) && res.result.length > 0) {
            // 创建一个Promise数组来等待所有文件加载完成
            const promises = res.result.map(fileName => {
              return this.loadSingleFile(fileName);
            });

            // 等待所有文件加载完成
            Promise.all(promises)
              .then(results => {
                // 过滤掉null值（被略过的文件）
                const validResults = results.filter(result => result !== null);
                if (validResults.length > 0) {
                  this.combineAndRenderTables();
                } else {
                  // 如果没有有效模板，可以显示提示信息
                  console.log("没有加载到有效的模板文件");
                  this.parsedTables = []; // 清空左侧表格显示
                }
              })
              .catch(error => {
                console.error("加载文件过程中出错");
                this.$message.error("加载文件过程中出错");
                this.parsedTables = []; // 出错时清空左侧表格显示
              });
          } else {
            // getTemplates 返回空数据时的处理
            console.log("未获取到模板文件");
            this.parsedTables = []; // 清空左侧表格显示
            // 可以显示提示信息
            this.$message.info("未找到相关模板文件");
          }
        })
        .catch(error => {
          console.error("获取模板失败", error);
          this.$message.error("获取模板失败");
          this.parsedTables = []; // 出错时清空左侧表格显示
        });
    },

    loadSingleFile(fileName) {
      const fileRes = {
        pageIndex: 1,
        query: {
          checkFactorIds: this.checkFactorIds,
          batchNumber: this.batchNumber
        },
        reportName: fileName
      };

      return new Promise((resolve, reject) => {
        batchesServer
          .loadData(fileRes)
          .then(res => {
            console.log("加载文件成功:", fileName, res);

            if (
              res.result &&
              res.result.content !== undefined &&
              res.result.style !== undefined
            ) {
              const fileData = {
                fileName: fileName,
                tableHtml: res.result.content,
                tableStyle: res.result.style
              };
              this.mockData.push(fileData);
              resolve(fileData);
            } else {
              console.warn(`文件返回空数据，已略过`);
              resolve(null);
            }
          })
          .catch(error => {
            console.error("加载文件失败");
            this.$message.error(`加载文件失败`);
            reject(error);
          });
      });
    },

    combineAndRenderTables() {
      if (this.mockData.length > 0) {
        // 清空之前的数据
        this.parsedTables = [];

        // 为每个表格单独解析和渲染（按原始顺序）
        this.mockData.forEach(data => {
          this.tableHtml = data.tableHtml;
          this.tableStyle = data.tableStyle;
          const parsedTable = this.parseSingleTable();
          if (parsedTable) {
            this.parsedTables.push(parsedTable);
          }
        });
      }
    },

    // 切换编辑模式
    toggleEditMode() {
      this.isEditMode = !this.isEditMode;

      // 如果进入编辑模式，初始化编辑数据
      if (this.isEditMode) {
        this.editedTables = [...this.parsedTables];
        this.$nextTick(() => {
          this.enableTableEditing();
        });
      } else {
        // 退出编辑模式时移除事件监听
        this.disableTableEditing();
      }
    },

    // 启用表格编辑功能
    enableTableEditing() {
      const tables = document.querySelectorAll(".dynamic-table.edit-mode");
      tables.forEach(table => {
        table.addEventListener("click", this.handleTableCellClick);

        const tds = table.querySelectorAll("td");
        tds.forEach(td => {
          // 检查是否包含特殊内容（如图片、公式等）
          const hasSpecialContent =
            td.querySelector("img") ||
            td.textContent.includes("×") ||
            td.textContent.includes("ρ") ||
            td.textContent.includes("M") ||
            td.textContent.includes("Vm") ||
            td.innerHTML.includes("<img") ||
            td.innerHTML.includes("<math") ||
            td.innerHTML.includes("<svg");

          // 对于包含特殊内容的单元格，不设置可编辑属性
          if (!hasSpecialContent) {
            td.setAttribute("contenteditable", "true");
            td.style.cursor = "text";

            // 处理空单元格中的不可见字符
            this.cleanInvisibleCharacters(td);
          } else {
            // 对于特殊内容，只添加视觉提示
            td.style.cursor = "not-allowed";
            td.title = "此单元格包含特殊内容，不可编辑";
          }

          td.addEventListener("focus", () => {
            if (!hasSpecialContent) {
              td.style.outline = "2px solid #409EFF";
            }
          });

          td.addEventListener("blur", () => {
            if (!hasSpecialContent) {
              td.style.outline = "none";
              // 失去焦点时再次清理不可见字符
              this.cleanInvisibleCharacters(td);
            }
          });

          // 添加输入事件监听器，处理输入过程中的不可见字符
          td.addEventListener("input", () => {
            if (!hasSpecialContent) {
              this.handleInputEvent(td);
            }
          });
        });
      });
    },

    // 清理单元格中的不可见字符
    cleanInvisibleCharacters(td) {
      // 如果单元格为空或只包含空白字符，则清空内容
      if (td.textContent.trim() === "") {
        td.textContent = "";
      } else {
        // 移除常见的不可见字符，但保留用户输入的内容
        const text = td.textContent;
        // 移除零宽空格、零宽非断空格等不可见字符
        const cleanedText = text.replace(/[\u200B-\u200D\uFEFF]/g, "");
        if (cleanedText !== text) {
          td.textContent = cleanedText;
        }
      }
    },

    // 处理输入事件
    handleInputEvent(td) {
      // 防止输入不可见字符
      const text = td.textContent;
      const cleanedText = text.replace(/[\u200B-\u200D\uFEFF]/g, "");
      if (cleanedText !== text) {
        td.textContent = cleanedText;
        // 将光标移到末尾
        const range = document.createRange();
        const sel = window.getSelection();
        range.selectNodeContents(td);
        range.collapse(false);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    },

    // 处理单元格点击事件 - 修改版
    handleTableCellClick(event) {
      if (!this.isEditMode) return;

      const target = event.target;
      if (target.tagName === "TD") {
        // 点击时清理不可见字符
        this.cleanInvisibleCharacters(target);
        target.focus();
      }
    },

    // 禁用表格编辑功能
    disableTableEditing() {
      const tables = document.querySelectorAll(".dynamic-table");
      tables.forEach(table => {
        table.removeEventListener("click", this.handleTableCellClick);

        const tds = table.querySelectorAll("td");
        tds.forEach(td => {
          td.removeAttribute("contenteditable");
          td.style.cursor = "";
          td.style.outline = "";
        });
      });
    },

    // 处理单元格点击事件
    handleTableCellClick(event) {
      if (!this.isEditMode) return;

      const target = event.target;
      if (target.tagName === "TD") {
        target.focus();
      }
    },

    // 下载编辑后的表格（多种格式）
    downloadEditedTableAs(format) {
      if (!this.parsedTables || this.parsedTables.length === 0) {
        this.$message.warning("没有可下载的表格数据");
        return;
      }

      switch (format) {
        case "html":
          this.downloadAsHTML();
          break;
        case "xlsx":
          this.downloadAsExcel();
          break;
        case "word":
          this.downloadAsWord();
          break;
        case "pdf":
          this.downloadAsPDF();
          break;
        default:
          this.downloadAsHTML();
      }
    },

    // 下载为HTML格式
    downloadAsHTML() {
      // 获取当前页面的表格内容
      const tables = document.querySelectorAll(".dynamic-table");

      // 创建完整的HTML文档
      let htmlContent = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>实验原始记录表</title>
  <style>
    body { font-family: Arial, sans-serif; }
    table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
    th, td { border: 1px solid #000; padding: 5px; text-align: center; }
    .table-divider { height: 20px; }
  </style>
</head>
<body>
`;

      tables.forEach((table, index) => {
        htmlContent += table.outerHTML;
        if (index < tables.length - 1) {
          htmlContent += '<div class="table-divider"></div>';
        }
      });

      htmlContent += `
</body>
</html>`;

      // 创建Blob对象并下载
      const blob = new Blob([htmlContent], { type: "text/html;charset=utf-8" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `原始记录表_${new Date()
        .toISOString()
        .slice(0, 10)}.html`;
      link.click();

      // 清理URL对象
      setTimeout(() => {
        URL.revokeObjectURL(url);
      }, 100);

      this.$message.success("HTML表格下载成功");
    },

    // 下载为Excel格式（通过HTML表格实现兼容Excel的格式）
    downloadAsExcel() {
      // 获取当前页面的表格内容
      const tables = document.querySelectorAll(".dynamic-table");

      // 创建兼容Excel的HTML表格
      let excelContent = `
<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40">
<head>
  <meta charset="UTF-8">
  <!--[if gte mso 9]>
  <xml>
    <x:ExcelWorkbook>
      <x:ExcelWorksheets>
        <x:ExcelWorksheet>
          <x:Name>实验原始记录表</x:Name>
          <x:WorksheetOptions>
            <x:DisplayGridlines/>
          </x:WorksheetOptions>
        </x:ExcelWorksheet>
      </x:ExcelWorksheets>
    </x:ExcelWorkbook>
  </xml>
  <![endif]-->
  <style>
    table { border-collapse: collapse; }
    th, td { border: 1px solid #000; padding: 5px; text-align: center; }
  </style>
</head>
<body>
`;

      tables.forEach((table, index) => {
        excelContent += table.outerHTML;
        if (index < tables.length - 1) {
          excelContent += '<div style="height: 20px;"></div>';
        }
      });

      excelContent += `
</body>
</html>`;

      // 创建Blob对象并下载
      const blob = new Blob([excelContent], {
        type: "application/vnd.ms-excel;charset=utf-8"
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `原始记录表_${new Date()
        .toISOString()
        .slice(0, 10)}.xlsx`;
      link.click();

      // 清理URL对象
      setTimeout(() => {
        URL.revokeObjectURL(url);
      }, 100);

      this.$message.success("Excel表格下载成功");
    },

    // 下载为Word格式
    downloadAsWord() {
      // 获取当前页面的表格内容
      const tables = document.querySelectorAll(".dynamic-table");

      // 创建Word兼容的HTML文档
      let wordContent = `
<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:w="urn:schemas-microsoft-com:office:word"
      xmlns="http://www.w3.org/TR/REC-html40">
<head>
  <meta charset="UTF-8">
  <title>实验原始记录表</title>
  <!--[if gte mso 9]>
  <xml>
    <w:WordDocument>
      <w:View>Print</w:View>
      <w:Zoom>100</w:Zoom>
    </w:WordDocument>
  </xml>
  <![endif]-->
  <style>
    @page {
      size: A4;
      margin: 1in 1in 1in 1in;
    }
    body {
      font-family: Arial, sans-serif;
      max-width: 8.5in;
      margin: 0 auto;
    }
    table {
      border-collapse: collapse;
      width: 100%;
      margin-bottom: 20px;
    }
    th, td {
      border: 1px solid #000;
      padding: 5px;
      text-align: center;
    }
    .table-divider {
      height: 20px;
    }
    h1 {
      text-align: center;
      color: #333;
    }
    h3 {
      text-align: center;
      color: #666;
    }
  </style>
</head>
<body>
`;

      tables.forEach((table, index) => {
        wordContent += table.outerHTML;
        if (index < tables.length - 1) {
          wordContent += '<div class="table-divider"></div>';
        }
      });

      wordContent += `
</body>
</html>`;

      // 创建Blob对象并下载
      const blob = new Blob([wordContent], {
        type: "application/msword;charset=utf-8"
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `原始记录表_${new Date()
        .toISOString()
        .slice(0, 10)}.docx`;
      link.click();

      // 清理URL对象
      setTimeout(() => {
        URL.revokeObjectURL(url);
      }, 100);

      this.$message.success("Word文档下载成功");
    },

    // 下载为PDF格式（通过浏览器打印功能实现）
    downloadAsPDF() {
      // 创建一个新的窗口用于打印
      const printWindow = window.open("", "_blank");

      // 获取当前页面的表格内容
      const tables = document.querySelectorAll(".dynamic-table");

      // 创建用于打印的HTML内容
      let printContent = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>实验原始记录表</title>
  <style>
    @media print {
      @page {
        size: A4;
        margin: 0.5in;
      }
      body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0.5in;
        color: black;
      }
    }

    body {
      font-family: Arial, sans-serif;
      max-width: 8.5in;
      margin: 0 auto;
      padding: 0.5in;
      color: black;
    }

    table {
      border-collapse: collapse;
      width: 100%;
      margin-bottom: 20px;
    }

    th, td {
      border: 1px solid #000;
      padding: 5px;
      text-align: center;
    }

    .table-divider {
      height: 20px;
    }

    h1 {
      text-align: center;
      color: #333;
    }

    h3 {
      text-align: center;
      color: #666;
    }
  </style>
</head>
<body onload="window.print()">
`;

      tables.forEach((table, index) => {
        printContent += table.outerHTML;
        if (index < tables.length - 1) {
          printContent += '<div class="table-divider"></div>';
        }
      });

      printContent += `
</body>
</html>`;

      printWindow.document.write(printContent);
      printWindow.document.close();

      // 等待打印完成后再关闭窗口
      setTimeout(() => {
        printWindow.close();
      }, 1000);

      this.$message.success("PDF文档准备打印，浏览器将自动弹出打印对话框");
    },

    parseSingleTable() {
      if (!this.tableHtml) return null;

      const parser = new DOMParser();
      const doc = parser.parseFromString(this.tableHtml, "text/html");
      const table = doc.querySelector("table");

      if (!table) return null;

      // 应用样式
      if (this.tableStyle) {
        // 创建一个临时的样式元素来解析CSS类
        const styleElement = document.createElement("style");
        styleElement.innerHTML = this.tableStyle;
        document.head.appendChild(styleElement);

        // 遍历所有带类名的td元素，将类样式转换为内联样式
        const cells = table.querySelectorAll("td[class]");
        cells.forEach(cell => {
          const className = cell.className;
          const cssClass = this.tableStyle.match(
            new RegExp(`\\.${className}\\{([^}]+)\\}`, "i")
          );
          if (cssClass) {
            // 将CSS规则转换为内联样式
            const rules = cssClass[1].split(";");
            rules.forEach(rule => {
              if (rule.trim()) {
                const [property, value] = rule.split(":");
                if (property && value) {
                  // 处理CSS属性名，转换为camelCase
                  let propName = property
                    .trim()
                    .replace(/-([a-z])/g, g => g[1].toUpperCase());
                  cell.style[propName] = value.trim();
                }
              }
            });
          }
        });

        // 移除临时样式元素
        document.head.removeChild(styleElement);
      }

      return table.outerHTML;
    },
    updateStyle() {
      if (this.batchNumber && this.batchNumber != "") {
        batchesServer
          .getCheckFactorByBatchNumberDetail({
            batchNumber: this.batchNumber,
            checkFactorIds: this.checkFactorIds
          })
          .then(res => {
            if (res.code === 200) {
              // 将 checkRes 转换为对象
              const resultData = res.result;
              if (resultData && Array.isArray(resultData)) {
                resultData.forEach(item => {
                  // 处理主因子
                  if (item.checkRes && typeof item.checkRes === "string") {
                    try {
                      item.checkRes = JSON.parse(item.checkRes);
                      item.checkRes.name =
                        item.checkRes.name || item.factorName;
                      item.checkRes.v1 = item.checkRes.v1 || 0;
                      item.checkRes.v2 = item.checkRes.v2 || 0;
                    } catch (e) {
                      console.warn("checkRes 解析失败:", e);
                      item.checkRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                    }
                  } else if (!item.checkRes) {
                    item.checkRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                  }

                  // 处理因子套餐中的 checkSubRes (注意：factorSubsetVos 是对象而不是数组)
                  if (item.factorSubsetVos) {
                    // 如果 factorSubsetVos 是对象
                    if (!Array.isArray(item.factorSubsetVos)) {
                      const subItem = item.factorSubsetVos;
                      if (
                        subItem.checkSubRes &&
                        typeof subItem.checkSubRes === "string"
                      ) {
                        try {
                          subItem.checkSubRes = JSON.parse(subItem.checkSubRes);
                          subItem.checkSubRes.name =
                            subItem.checkSubRes.name || subItem.factorName;
                          subItem.checkSubRes.v1 = subItem.checkSubRes.v1 || 0;
                          subItem.checkSubRes.v2 = subItem.checkSubRes.v2 || 0;
                        } catch (e) {
                          console.warn("checkSubRes 解析失败:", e);
                          subItem.checkSubRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                        }
                      } else if (!subItem.checkSubRes) {
                        subItem.checkSubRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                      }
                    }
                    // 如果 factorSubsetVos 是数组
                    else if (Array.isArray(item.factorSubsetVos)) {
                      item.factorSubsetVos.forEach(subItem => {
                        if (
                          subItem.checkSubRes &&
                          typeof subItem.checkSubRes === "string"
                        ) {
                          try {
                            subItem.checkSubRes = JSON.parse(
                              subItem.checkSubRes
                            );
                            subItem.checkSubRes.name =
                              subItem.checkSubRes.name || subItem.factorName;
                            subItem.checkSubRes.v1 =
                              subItem.checkSubRes.v1 || 0;
                            subItem.checkSubRes.v2 =
                              subItem.checkSubRes.v2 || 0;
                          } catch (e) {
                            console.warn("checkSubRes 解析失败:", e);
                            subItem.checkSubRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                          }
                        } else if (!subItem.checkSubRes) {
                          subItem.checkSubRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                        }
                      });
                    }
                  }
                });
              }
              this.batchData = resultData;

              // 添加回显逻辑
              if (
                res.result &&
                res.result.length > 0 &&
                res.result[0].checkEquipment
              ) {
                try {
                  const equipment = JSON.parse(res.result[0].checkEquipment);
                  if (equipment) {
                    // 设置仪器分类
                    this.equipmentType = equipment.equipmentName;

                    // 触发第一级联动，加载第二级选项
                    this.handleChangeEqu(this.equipmentType);

                    // 设置仪器型号
                    this.equipmentClass = equipment.equipmentModel;

                    // 触发第二级联动，加载第三级选项
                    this.handleChangeEquType(this.equipmentClass);

                    // 设置仪器编号（整个对象）
                    this.checkEquipment = equipment.equipmentNumber;
                    this.checkEquipmentname = equipment;
                  }
                } catch (e) {
                  console.warn("设备信息解析失败:", e);
                }
              }
            }
          });
      }
    },
    getEquipment() {
      this.level = [];
      this.levelTwo = [];
      this.levelThree = [];
      batchesServer.laboratoryEquipmentTree().then(res => {
        if (res.result) {
          const treeData = res.result ? res.result : [];
          if (treeData !== "") {
            this.level = treeData;
          }
        }
      });
    },
    handleChangeEqu(val) {
      this.equipmentClass = [];
      this.checkEquipment = [];
      this.levelTwo = [];
      this.levelThree = [];
      const o = this.level.find(i => i.name === val);
      if (o) {
        this.levelTwo = o.children || [];
      }
    },
    handleChangeEquType(val) {
      this.checkEquipment = [];
      this.levelThree = [];
      const o = this.levelTwo.find(i => i.name === val);
      if (o) {
        this.levelThree = o.children || [];
      }
    },
    //人员选择
    handleCreate() {
      List.userList().then(res => {
        this.usernameOptions = res.result;
      });
    },

    cancel() {
      // 清空所有选择的数据
      this.equipmentType = "";
      this.equipmentClass = "";
      this.checkEquipment = "";
      this.checkEquipmentname = ""; // 清除设备名称缓存
      this.level = []; // 清除第一级设备分类
      this.levelTwo = []; // 清除第二级设备分类
      this.levelThree = []; // 清除第三级设备编号
      this.flatDataList = [];

      // 清空表单数据
      if (this.batchData && Array.isArray(this.batchData)) {
        this.batchData.forEach(item => {
          if (item.checkRes) {
            item.checkRes.v1 = "";
            item.checkRes.v2 = "";
          }

          // 清空因子套餐中的数据
          if (item.factorSubsetVos && Array.isArray(item.factorSubsetVos)) {
            item.factorSubsetVos.forEach(subItem => {
              if (subItem.checkSubRes) {
                subItem.checkSubRes.v1 = "";
                subItem.checkSubRes.v2 = "";
              }
            });
          }
        });
      }

      // 清空复核人选择
      this.reviewer = "";
      this.reviewDialogVisible  = false;
      this.sampleSelectDialogVisible   = false;

      // 清空仪器相关的表单引用（如果有的话）
      if (this.$refs.equipmentForm) {
        this.$refs.equipmentForm.resetFields();
      }

      this.$router
        .push({
          name: "BatchDetail",
          params: {
            batchNumber: this.batchNumber,
            checkFactorId: this.checkFactorId,
            checkFactorIds: this.checkFactorIds,
            checkTaskId: this.checkTaskId,
            jobId: this.jobId
          }
        })
        .catch(err => {
          console.error("路由跳转失败:", err);
          this.$message.error("页面跳转失败");
        });
    },
    //处理数据
    dispose() {
      this.flatDataList = []; // 初始化为空数组

      this.batchData.forEach(item => {
        if (item.isFactor == 0) {
          // 主因子数据
          this.flatDataList.push({
            checkFactorId: item.checkFactorId,
            remark: item.remark,
            checkRes: JSON.stringify(item.checkRes)
          });
        } else if (item.isFactor == 1 && item.factorSubsetVos) {
          // 因子套餐数据处理
          const factorData = {
            checkFactorId: item.checkFactorId,
            remark: item.remark,
            factorSubsetVos: []
          };

          // 处理 factorSubsetVos 是单个对象的情况
          if (!Array.isArray(item.factorSubsetVos)) {
            const subItem = item.factorSubsetVos;
            factorData.factorSubsetVos.push({
              id: subItem.id,
              factorName: subItem.factorName,
              checkStandardId: subItem.checkStandardId,
              standardNo: subItem.standardNo,
              standardName: subItem.standardName,
              checkSubRes: JSON.stringify(subItem.checkSubRes),
              unitName: subItem.unitName
            });
          }
          // 处理 factorSubsetVos 是数组的情况
          else if (Array.isArray(item.factorSubsetVos)) {
            item.factorSubsetVos.forEach(subItem => {
              factorData.factorSubsetVos.push({
                id: subItem.id,
                factorName: subItem.factorName,
                checkStandardId: subItem.checkStandardId,
                standardNo: subItem.standardNo,
                standardName: subItem.standardName,
                checkSubRes: JSON.stringify(subItem.checkSubRes),
                unitName: subItem.unitName
              });
            });
          }

          this.flatDataList.push(factorData);
        }
      });
    },
    save() {
      this.dispose();
      let checkEquipmentValue = null;

      if (typeof this.checkEquipment === "string") {
        checkEquipmentValue = JSON.stringify(this.checkEquipmentname);
      } else {
        checkEquipmentValue = JSON.stringify(this.checkEquipment);
      }

      const checkFactorInfoTdos = {
        checkEquipment: checkEquipmentValue,
        checkFactorInfoTdos: this.flatDataList
      };
      batchesServer.batchSaveCheckFactor(checkFactorInfoTdos).then(res => {
        if (res.code == 200) {
          this.$notify({
            title: "成功",
            message: res.message,
            type: "success"
          });
          this.updateStyle();
          this.handleSearch();
          this.dialogVisible = false;
        } else {
          this.$notify({
            title: "失败",
            message: res.message,
            type: "error"
          });
        }
      });
    },

    submit() {
      this.dispose();
      if (this.checkBeforeSelectReviewer()) {
        // 检查通过，显示复核人选择对话框
        this.reviewDialogVisible  = true;
      }
    },
    checkBeforeSelectReviewer() {
      // 检查检测仪器是否已选择
      if (!this.checkEquipment) {
        this.$message.warning("请选择检测仪器");
        return false;
      }

      // 检查因子数据是否存在
      if (!this.batchData || this.batchData.length === 0) {
        this.$message.warning("没有可提交的数据");
        return false;
      }
      return true;
    },
    confirmSubmit() {
      if (!this.reviewer) {
        this.$message.warning("请选择复核人");
        return;
      }
      // 检查检测仪器是否已选择
      if (!this.checkEquipment) {
        this.$message.warning("请选择检测仪器");
        return;
      }
      let checkEquipmentValue = null;

      if (typeof this.checkEquipment === "string") {
        checkEquipmentValue = JSON.stringify(this.checkEquipmentname);
      } else {
        checkEquipmentValue = JSON.stringify(this.checkEquipment);
      }

      const checkFactorInfoTdos = {
        checkEquipment: checkEquipmentValue,
        checkFactorInfoTdos: this.flatDataList
      };
      batchesServer.batchSaveCheckFactor(checkFactorInfoTdos).then(res => {
        if (res.code == 200) {
          this.$notify({
            title: "成功",
            message: res.message,
            type: "success"
          });
          this.submitData();
          this.reviewDialogVisible  = false;
        } else {
          this.$notify({
            title: "失败",
            message: res.message,
            type: "error"
          });
        }
      });
      this.reviewDialogVisible  = false;
    },
    submitData() {
      const params = {
        checkFactorIds: this.checkFactorIds,
        batchNumber: this.batchNumber,
        reviewUserId: this.reviewer
      };
      batchesServer.reviewCheckFactor(params).then(res => {
        if (res.code == 200) {
          this.equipmentType = null;
          this.checkEquipment = null;
          this.equipmentClass = null;
          this.checkEquipmentValue = null;
          this.$notify({
            title: "成功",
            message: res.message,
            type: "success"
          });

          // 跳转到批次详情页面，并携带所需参数
          this.$router
            .push({
              name: "BatchDetail",
              params: {
                batchNumber: this.batchNumber,
                checkFactorId: this.checkFactorId,
                checkFactorIds: this.checkFactorIds,
                checkTaskId: this.checkTaskId,
                jobId: this.jobId
              }
            })
            .catch(err => {
              console.error("路由跳转失败:", err);
              this.$message.error("页面跳转失败");
            });

          this.reviewer = ""; // 清空选择
          this.dialogVisible = false;
        } else {
          this.$notify({
            title: "失败",
            message: res.message,
            type: "error"
          });
        }
      });
    },

    // 打开文件上传弹框
    openFileUploadDialog() {
      // 构造当前行数据，从路由参数中获取
      this.currentRow = {
        fileResourceId: this.$route.params.batcData.fileResourceId || "",
        fileResourceCode: this.$route.params.batcData.fileResourceCode || "",
        batchNumber: this.$route.params.batchNumber || "",
        sampleNos: this.$route.params.batcData.sampleNos || ""
      };

      this.selectedFile = null;

      // 设置原始文件URL（从路由参数或其他数据源获取）
      // 这里假设从路由参数的 batcData 中获取 originalUrl
      this.originalUrl = this.$route.params.batcData.originalUrl || "";

      // 根据 fileResourceCode 判断处理逻辑
      if (this.currentRow.fileResourceCode === "SYS_TOC") {
        // SYS_TOC: 直接上传，不需要选择样品号
        this.selectedSampleNo = ""; // 不需要样品号
        this.showFileUploadDialog();
        return;
      } else {
        // 处理样品号选择逻辑
        const sampleNos = this.currentRow.sampleNos
          ? this.currentRow.sampleNos
              .split(",")
              .map(no => no.trim())
              .filter(no => no !== "")
          : [];

        // 如果只有一个样品号，直接使用
        if (sampleNos.length === 1) {
          this.selectedSampleNo = sampleNos[0];
          this.showFileUploadDialog();
        }
        // 如果有多个样品号，显示弹框选择
        else if (sampleNos.length > 1) {
          this.sampleOptions = sampleNos;
          this.sampleSelectDialogVisible  = true;
          this.selectedSampleNo = ""; // 清空之前的选择
        }
        // 如果没有样品号，直接打开文件上传
        else {
          this.selectedSampleNo = "";
          this.showFileUploadDialog();
        }
      }
    },

    // 显示文件上传对话框
    showFileUploadDialog() {
      this.fileUploadVisible = true;
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      });
    },

    // 确认样品号选择
    confirmSampleSelection() {
      if (!this.selectedSampleNo) {
        this.$message.warning("请选择样品号");
        return;
      }

      this.sampleSelectDialogVisible  = false;
      // 打开文件上传弹框
      this.showFileUploadDialog();
    },

    // 处理文件选择变化
    handleFileChange(file) {
      this.selectedFile = file.raw;
    },

    // 确认文件上传
    async confirmFileUpload() {
      if (!this.selectedFile) {
        this.$message.warning("请选择要上传的文件");
        return;
      }

      if (!this.currentRow) {
        this.$message.error("未选择样品信息");
        return;
      }

      const formData = new FormData();
      formData.append("file", this.selectedFile);

      try {
        // 根据 fileResourceCode 判断调用不同的参数
        let response;
        if (this.currentRow.fileResourceCode === "SYS_TOC") {
          // SYS_TOC 情况下不需要样品号
          response = await batchesServer.uploadOriginalRecord(
            formData,
            this.checkFactorIds,
            "", // 空的样品号
            this.currentRow.fileResourceId,
            this.currentRow.batchNumber
          );
        } else {
          response = await batchesServer.uploadOriginalRecord(
            formData,
            this.checkFactorIds,
            this.selectedSampleNo,
            this.currentRow.fileResourceId,
            this.currentRow.batchNumber
          );
        }

        if (response.code === 200) {
          this.$message.success("结果录入成功");
          this.fileUploadVisible = false;

          // 更新originalUrl为新上传的文件URL
          if (response.result && response.result.length > 0) {
            this.originalUrl = response.result[0]; // 假设返回的数组第一个元素是文件URL
          }

          // 刷新数据
          this.updateStyle();
          this.handleSearch();

          // 清空相关数据
          this.selectedFile = null;
          this.currentRow = null;
        } else {
          this.$message.error(response.message);
        }
      } catch (error) {
        console.error(error);
        this.$message.error("上传过程中发生错误");
      }
    },

    // 原始记录上传前检查
    beforeOriginalRecordUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("文件大小不能超过 10MB!");
        return false;
      }
      return true;
    },
    // 打开上传原始记录表弹框
     openSpectrumUpload() {
      this.spectrumDialogVisible = true;
      this.spectrumFileList = [];

      // 如果已有上传的文件，进行回显
      this.fetchExistingSpectrumFiles(this.$route.params.batcData);
    },

    // 获取已存在的谱图文件进行回显
    fetchExistingSpectrumFiles(row) {
      // 检查行数据中是否有 originalUrl 字段
      if (row.originalUrl) {
        // 解析 originalUrl 字段，通常是逗号分隔的文件URL列表
        const urls = row.originalUrl.split(",").filter(url => url.trim() !== "");

        // 构造文件列表用于回显
        this.spectrumFileList = urls.map((url, index) => {
          // 从URL中提取文件名，如果没有则使用默认名称
          const fileName =
            this.extractFileNameFromUrl(url) || `附件${index + 1}`;

          return {
            name: fileName,
            url: url.trim(),
            status: "success" // 标记为已上传成功状态
          };
        });
      }
    },
    extractFileNameFromUrl(url) {
      if (!url) return "";

      // 尝试从URL中提取文件名
      const urlParts = url.split("/");
      const fileName = urlParts[urlParts.length - 1];

      // 如果文件名存在且不为空
      if (fileName && fileName !== "") {
        return decodeURIComponent(fileName);
      }

      return "";
    },

    // 处理谱图文件预览
    // handleSpectrumPreview(file) {
    //   window.open(file.url);
    // },

    // 处理谱图文件移除
    handleSpectrumRemove(file, fileList) {
      this.spectrumFileList = fileList;
    },

    // 移除文件前确认
    beforeSpectrumRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 处理谱图文件变化
    handleSpectrumChange(file, fileList) {
      this.spectrumFileList = fileList;
    },

    // 添加文件上传成功的处理方法
    handleSpectrumSuccess(response, file, fileList) {
      if (response && response.code === 200) {
        // 为上传成功的文件添加URL
        file.url = response.result[0];
        this.$message.success(`文件 ${file.name} 上传成功`);

        // 增加成功计数
        this.uploadSuccessCount++;
      } else {
        this.$message.error(response.message || `文件 ${file.name} 上传失败`);
        this.uploadFailedCount++;
      }

      // 检查是否所有文件都已处理完成
      if (
        this.uploadSuccessCount + this.uploadFailedCount ===
        this.uploadTotalCount
      ) {
        // 所有文件处理完成
        if (this.uploadFailedCount === 0) {
          // 全部成功，调用 checkFactor
          this.checkFactor();
        } else {
          // 全部失败
          this.$message.error("所有文件上传失败，无法提交");
        }
      }
    },
    // 谱图文件上传前检查
    beforeSpectrumUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("文件大小不能超过 10MB!");
        return false;
      }
      return true;
    },

    // 提交谱图文件
    submitSpectrumFiles() {
      // 获取所有需要上传的文件（排除已经成功的文件）
      const filesToUpload = this.spectrumFileList.filter(file => !file.url);

      // // 即使没有新文件也要允许提交，但需要有文件存在
      // if (this.spectrumFileList.length === 0) {
      //   this.$message.warning("请至少选择一个文件");
      //   return;
      // }

      // 如果有新文件需要上传，则初始化上传计数器并触发上传
      if (filesToUpload.length > 0) {
        this.uploadSuccessCount = 0;
        this.uploadTotalCount = filesToUpload.length;
        this.uploadFailedCount = 0;

        // 触发上传
        this.$refs.spectrumUpload.submit();
      } else {
        // 没有新文件需要上传，直接调用checkFactor提交现有文件
        this.checkFactor();
      }
    },

    checkFactor() {
      // 收集所有文件的URL（包括已存在的和新上传的）
      const uploadedUrls = this.spectrumFileList
        .filter(file => file.url) // 只选择有URL的文件
        .map(file => file.url);

      // if (uploadedUrls.length === 0) {
      //   this.$message.warning("没有可提交的文件");
      //   return;
      // }

      batchesServer
        .uploadOriginalFile({
          batchNumber: this.batchNumber,
          checkFactorIds: this.checkFactorIds,
          batchUrl: uploadedUrls.join(",")
        })
        .then(res => {
          console.log(res);
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "上传成功!"
            });
            this.handleSearch();
            // 关闭弹框
            this.spectrumDialogVisible = false;
          } else {
            this.$message.error("上传失败!");
          }
        })
        .catch(err => {
          console.error(err);
          this.$message.error("上传失败!");
        });
    },

    // 关闭弹框时的处理
    handleSpectrumDialogClose() {
      this.spectrumFileList = [];
      if (this.$refs.spectrumUpload) {
        this.$refs.spectrumUpload.clearFiles();
      }
    }
  }
};
</script>

<style scoped>
.result-entry-container {
  display: flex;
  height: 92vh;
}

.left-form {
  flex: 2;
  padding: 20px;
  overflow-y: auto; /* 添加垂直滚动条 */
  border-right: 1px solid #ddd;
  max-height: 100vh; /* 限制最大高度 */
  height: auto; /* 自动高度 */
  min-height: 500px; /* 最小高度 */
}

.dynamic-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.dynamic-table td {
  padding: 8px;
  border: 1px solid #ccc;
  text-align: left;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: inline-block;
  width: 100px;
  font-weight: bold;
}

.form-group input[type="text"],
.form-group select,
.form-group input[type="number"] {
  padding: 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.button-group {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  /* 防止按钮组被滚动影响 */
  flex-shrink: 0;
}

.button-group button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.button-group button:nth-child(1) {
  background-color: #ccc;
}

.button-group button:nth-child(2) {
  background-color: #007bff;
  color: white;
}

.button-group button:nth-child(3) {
  background-color: #28a745;
  color: white;
}
.table-divider {
  margin: 20px 0;
  border-top: 1px dashed #ccc;
}
.result-tips {
  margin-top: 10px;
}

.tip-item {
  font-size: 12px;
  color: #ff0000; /* 警告色 */
  font-weight: bold; /* 加粗 */
  line-height: 1.5;
}

.tip-warning {
  color: #ff0000; /* 警告色 */
  font-weight: bold; /* 加粗 */
}
.result-entry-container {
  display: flex;
  height: 92vh;
  width: 100%;
}

/* 新增右侧容器样式 */
.right-form-container {
  width: 700px;
}

.right-form {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background: #dedede;
  scrollbar-gutter: stable; /* 添加这行 */
}

/* 隐藏 Webkit 浏览器滚动条 */
.right-form::-webkit-scrollbar {
  width: 0;
  height: 0;
  background: transparent;
}

.sample-group {
  flex: 1;
  overflow-y: auto;
  max-height: calc(100vh - 300px);
  margin-bottom: 20px;
}

.button-group {
  margin-top: auto; /* 将按钮组推到底部 */
  display: flex;
  gap: 10px;
  flex-shrink: 0;
  padding: 10px 0;
}

/* 响应式输入框 */
@media (max-width: 1400px) {
  .result-value-input,
  .exponent-input {
    max-width: 150px;
  }
}

@media (max-width: 1200px) {
  .result-value-input,
  .exponent-input {
    max-width: 100%;
    width: 100%;
  }
}

/* 确保表单在小屏幕上正常显示 */
@media (max-width: 768px) {
  .right-form {
    padding: 10px;
  }

  .sample-group .el-col {
    width: 100%;
    margin-left: 0 !important;
    margin-bottom: 10px;
  }

  .button-group {
    flex-direction: column;
  }
}

/* 确保表单元素自适应 */
.right-form .el-form {
  flex: 0;
  display: flex;
  flex-direction: column;
}

.right-form .el-form-item {
  margin-bottom: 0px !important;
}

/* 确保输入框自适应宽度 */
.right-form .el-input {
  width: 100%;
}

/* 调整检测结果输入框的宽度 */
.result-value-input,
.exponent-input {
  width: 100%;
  max-width: 200px;
}
.text-ellipsis {
  display: inline-block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}
/* 必填星号样式 */
.required-star {
  color: #f56c6c;
  margin-left: 4px;
}

/* 表单验证错误样式 */
.el-form-item.is-error .el-select .el-input__inner {
  border-color: #f56c6c;
}

/* 表单验证成功样式 */
.el-form-item.is-success .el-select .el-input__inner {
  border-color: #67c23a;
}

.factor-single {
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.factor-package {
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.1);
}

.factor-package-item {
  background-color: #ffffff;
  border: 1px solid #e0e9f0;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
  border-radius: 15px;
}

.factor-package-item:hover {
  background-color: #f5faff;
  box-shadow: 0 1px 4px rgba(64, 158, 255, 0.15);
  border-radius: 15px;
}

.factor-single:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.factor-package:hover {
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

/* 为编辑模式下的空单元格添加更好的视觉提示 */
.dynamic-table.edit-mode td:empty:before {
  content: "\00a0"; /* 使用非断行空格作为占位符 */
  visibility: hidden;
}

.dynamic-table.edit-mode td:focus:empty:before {
  content: ""; /* 聚焦时清除占位符 */
}

/* 可选：为编辑模式下的空单元格添加虚线边框提示 */
.dynamic-table.edit-mode td:empty {
  border: 1px dashed #ccc !important;
}
</style>
